const initialState = {
  //文章评论数据
  commentData: {} as commentData,
  //原始文章
  replyOriginData: {} as commentItem,
  //回复评论的数据
  replyCommentData: {} as commentData,
};

export default function commentReducer(state = initialState, action: any) {
  switch (action.type) {
    //获取评论数据和加载更多评论数据
    case 'comment/setCommentData':
      return {
        ...state,
        commentData: {
          ...action.payload,
          results: [...(state.commentData.results || []), ...action.payload.results],
        },
      };
    //清除评论数据
    case 'comment/clearCommentData':
      return {
        ...state,
        commentData: {} as commentData,
      };
    case 'comment/setReplyOriginData':
      return {
        ...state,
        replyOriginData: action.payload,
      };
    //追加新发送的评论到评论列表中
    case 'comment/appendAddCommentData':
      return {
        ...state,
        commentData: {
          ...state.commentData,
          results: [action.payload, ...(state.commentData.results || [])],
          total_count: state.commentData.total_count + 1,
        },
      };
    //评论点赞
    case 'comment/likeComment':
      const oldList = state.commentData.results || [];
      const newList = [...oldList];
      const findItem = newList.find((item) => item.com_id === action.payload);
      findItem!.is_liking = !findItem?.is_liking;
      findItem!.like_count += findItem?.is_liking ? 1 : -1;
      return {
        ...state,
        commentData: {
          ...state.commentData,
          results: newList,
        },
      };
    //获取回复评论的数据
    case 'comment/setReplyCommentData':
      return {
        ...state,
        replyCommentData: action.payload,
      };
    default:
      return state;
  }
}
export interface commentData {
  total_count: number;
  end_id: string;
  last_id: string;
  results: commentItem[];
}

export interface commentItem {
  com_id: string;
  content: string;
  reply_count: number;
  pubdate: string;
  is_followed: boolean;
  is_liking: boolean;
  like_count: number;
  aut_id: string;
  aut_name: string;
  aut_photo: string;
}
